package cn.z2huo.knowledge.security;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

/**
 *
 * @author z2huo
 */
public class MessageDigestTest {

    /**
     * 25f9e794323b453885f5181f1b624d0b
     * 25f9e794323b453885f5181f1b624d0b
     *
     * 15e2b0d3c33891ebb0f1ef609ec419420c20e320ce94c65fbc8c3312448eb225
     * 15e2b0d3c33891ebb0f1ef609ec419420c20e320ce94c65fbc8c3312448eb225
     *
     */
    public static void main(String[] args) {
        md5Test();
        System.out.println();
        sha256Test();
    }

    public static void md5Test() {
        String password = "123456789";
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            messageDigest.update(password.getBytes(StandardCharsets.UTF_8));
            byte[] digest = messageDigest.digest();
            String string = byte2Hex(digest);
            System.out.println(string);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
   }

    public static void sha256Test() {
        String password = "123456789";
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
            messageDigest.update(password.getBytes(StandardCharsets.UTF_8));
            byte[] digest = messageDigest.digest();
            String string = byte2Hex(digest);
            System.out.println(string);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    }

    private static String byte2Hex(byte[] bytes) {
        System.out.println(Arrays.toString(bytes) + " " + bytes.length);
        StringBuilder sb = new StringBuilder();
        String temp;
        for (byte aByte : bytes) {
//            temp = Integer.toHexString(aByte & 0xFF);
//            if (temp.length() == 1) {
//                // 1 得到一位的进行补 0 操作
//                sb.append("0");
//            }

            temp = Integer.toHexString((aByte & 0xFF) | 0x100).substring(1, 3);
            sb.append(temp);
        }
        return sb.toString();
    }
}
